package dk.dtu.android.transport.db;

import dk.dtu.android.transport.Helpers;
import dk.dtu.android.transport.TransportAPI;
import android.content.ContentValues;
import android.database.Cursor;

public class PendingRequestTable extends BaseDbAdapter {

	protected static String TABLE_NAME = "PENDING_REQUEST";
	
	protected static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (_id INTEGER PRIMARY KEY, url TEXT, json TEXT, sent INTEGER, created TEXT)";
	
	public PendingRequestTable(String key, String value) {
	}
	
	/* Static methods */
	
	public static void insert(String url, String json)
	{
		ContentValues args = new ContentValues();
		args.put("url", url);
		args.put("json", json);
		args.put("sent", 0);
		args.put("created", Helpers.ToXMLDate(null));
		
		db.insert(TABLE_NAME, null, args);
	}
	
	private static void update(int id, boolean sent)
	{
		ContentValues args = new ContentValues();
		args.put("sent", Helpers.boolToInteger(sent));
		db.update(TABLE_NAME, args, "_id = ?", new String[] {Integer.toString(id)});
	}
	
	public static int unsentCount()
	{
		Cursor cursor = db.query(TABLE_NAME, new String[] {"count(1)"}, "sent = ?", new String[] {"0"}, null, null, null);
		int count = 0;
		if (cursor.moveToFirst())
		{
			do {
				count = cursor.getInt(0);
			} while (cursor.moveToNext());
		}
		return count;
	}

	public static void sendUnsent()
	{
		Cursor cursor = db.query(TABLE_NAME, new String[] {"_id", "url", "json"}, "sent = ?", new String[] {"0"}, null, null, null);
		if (cursor.moveToFirst())
		{
			do {
				int _id = Integer.parseInt(cursor.getString(0));
				String url = cursor.getString(1);
				String json = cursor.getString(2);
				try
				{
					TransportAPI.post(url, json, false);
					update(_id, true);
				}
				catch(Exception e)
				{
				}
			} while (cursor.moveToNext());
		}
	}
}
